package org.example.algorithms.demo1;

import cn.hutool.core.collection.CollUtil;
import lombok.Data;

import java.util.Date;
import java.util.Random;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author Gong.Yang
 */
public class Demo {
    public static void main(String[] args) {
        ConcurrentLinkedQueue<RequestRecord>[] timeWell = new ConcurrentLinkedQueue[10];//时间轮
        int len = timeWell.length;
        new Thread(() -> {
            int current = 0;
            while (true) {
                try {
                    TimeUnit.SECONDS.sleep(1);
                    int i = len % current++;
                    if (CollUtil.isEmpty(timeWell[i])) continue;
                    RequestRecord record;
                    while ((record = timeWell[i].poll()) != null) {
                        //TODO 判断是否超时。
                        //TODO 超时逻辑
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }, "模拟 超时检测").start();
        new Thread(() -> {
            Random random = new Random();
            for (int i = 0; i < 100; i++) {
                int timeOut = random.nextInt(100) + 1;

                //根据超时时间放进指定槽位
                ConcurrentLinkedQueue<RequestRecord> queue = timeWell[timeOut % len];
                queue.add(new RequestRecord(timeOut));
            }
        }, "模拟 请求发起线程").start();
    }

    @Data
    static class RequestRecord {
        private int timeOut;//假如是秒为单位
        private Date createTime;
        //。。 其他信息


        public RequestRecord(int timeOut) {
            this.timeOut = timeOut;
            createTime = new Date();
        }
    }


}
